package com.heking.security.webview;

import android.graphics.Bitmap;
import android.net.Uri;
import android.net.http.SslError;
import android.os.Build;
import android.webkit.SslErrorHandler;
import android.webkit.WebResourceError;
import android.webkit.WebResourceRequest;
import android.webkit.WebResourceResponse;
import android.webkit.WebView;
import android.webkit.WebViewClient;

import com.heking.security.LogUtils;

/**
 *
 * WebViewClient 基类
 * @Author 35574
 * @Date 2021/10/25
 * @Description
 */
public abstract class BaseWebViewClient extends WebViewClient {
    private static final String TAG = ">>>BaseWebViewClient";

    /**
     * 显示加载框
     */
    public abstract void onLoading();

    /**
     * 关闭加载框
     */
    public abstract void onLoadingFinish();

    @Override
    public void onPageStarted(WebView view, String url, Bitmap favicon) {
        LogUtils.d(TAG, "==>onPageStarted:" + url);
        onLoading();
        super.onPageStarted(view, url, favicon);
    }

    @Override
    public void onPageFinished(WebView view, String url) {
        onLoadingFinish();
        LogUtils.d(TAG, "<==onPageFinished:"+url);
        super.onPageFinished(view, url);
    }

    @Override
    public void onReceivedError(WebView view, WebResourceRequest request, WebResourceError error) {
        onLoadingFinish();
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            LogUtils.e(TAG, "onReceivedError:"+(error!=null ?error.getDescription():""));
        }else{
            LogUtils.e(TAG, "onReceivedError:"+error);
        }

        super.onReceivedError(view, request, error);
    }

    @Override
    public void onReceivedSslError(WebView view, SslErrorHandler handler, SslError error) {
        LogUtils.e(TAG, "onReceivedSslError:"+error);
        /**
         * WebView 组件忽略 SSL 证书验证错误漏洞
         * 当发生证书认证错误时，在 WebViewClient.onReceivedSslError
         * 方法中调用默认的处理方法 handler.cancel()来停止加载问题页
         * 面。
         */
        handler.cancel();
    }

    @Override
    public void onReceivedHttpError(WebView view, WebResourceRequest request, WebResourceResponse errorResponse) {
        super.onReceivedHttpError(view, request, errorResponse);
    }


    protected String getUrl(WebResourceRequest request){
        if (request != null) {
            if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.LOLLIPOP) {
                Uri url = request.getUrl();
                return url!=null ?url.toString():null;
            }
        }
        return null;
    }



}
